﻿using System;
using System.Linq;
using NazTek.Core;

namespace NazTek.Repository
{
    /// <summary>
    /// Captures database context and logging delegate.
    /// </summary>
    public abstract class RepositoryBase<T> : IRepositoryBase where T : class, IEntity
    {
        /// <summary>
        /// Gets/sets database context.
        /// </summary>
        public IDbContext DbContext { get; set; }
        /// <summary>
        /// Gets/sets logging delegate.
        /// </summary>
        public Action<string> Log
        {
            get { return DbContext.Log; }
            set { DbContext.Log = value; }
        }
        /// <summary>
        /// locates single record based on specified criteria.
        /// </summary>
        /// <param name="criteria">search criteria.</param>
        /// <returns>Matched record when found, otherwise null.</returns>
        public T Find(Func<T, bool> criteria)
        {
            return DbContext.Set<T>().FirstOrDefault(criteria);
        }
        /// <summary>
        /// Disposes <see cref="DbContext"/>, when not null and suppresses garbage collector.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
        }
        /// <summary>
        /// Frees managed and native resources.
        /// </summary>
        /// <param name="disposing">Disposes managed resource, <see cref="DbContext"/>, when true.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing || DbContext == null)
                return;
            DbContext.Dispose();
            DbContext = null;
        }
    }
}